package org.skipper.samples.mybatis.plus.crud.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 测试，自定义元对象字段填充控制器，实现公共字段自动写入
 */
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 测试 user 表 name 字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        System.out.println("*************************");
        System.out.println("insert of mysql fill");
        System.out.println("*************************");
        // 测试下划线
        Object createTime = this.getFieldValByName("createTime", metaObject);
        //如果已经有了对应的值，则不覆盖
        if (createTime == null) {
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        System.out.println("*************************");
        System.out.println("update of mysql fill");
        System.out.println("*************************");
        //测试实体没有的字段，配置在公共填充，不应该set到实体里面
        Object updateTime = this.getFieldValByName("updateTime", metaObject);

        if (updateTime == null) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }

    }

    @Override
    public TableInfo findTableInfo(MetaObject metaObject) {
        return TableInfoHelper.getTableInfo(metaObject.getOriginalObject().getClass());
    }
}

